import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { get as lodashGet } from 'lodash-es';
import router from "@/router"
import { useUserStore } from "@/store/modules/user"

const baseURL = '';
function createService(): AxiosInstance {
    const service = axios.create({
        baseURL
    });

    // 请求拦截器
    service.interceptors.request.use(config => {
        const { token } = useUserStore()
        // const accessToken = localStorage.getItem("ACCESS-TOKEN");

        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    }, error => {
        return Promise.reject(error);
    });

    // 响应拦截器
    service.interceptors.response.use(response => {
        if(response.data.code == 500) {
            $message.error('服务器出问题了，请稍后再试');
        }
        return response;
    }, error => {
        const { response } = error;

        if (response && response.status === 401 && response.data.msg === 'token验证错误') {
            // 处理登录失效
            handleUnauthorized();
        }

        return Promise.reject(error);
    });
    

    const { $message } = window as any;

    service.interceptors.request.use(config => config, error => {
        $message.error('网络不给力，请稍后再试');
        return Promise.reject(error);
    });
    
    return service;
}

type AxiosMethod = 'get' | 'post' | 'put' | 'delete';
function createRequest(service: AxiosInstance) {
    const makeRequest = async <T = any>(method: AxiosMethod, url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
        const headers = {
            'Content-Type': 'application/json',
            ...lodashGet(config, 'headers', {})
        };
        
        return service.request<T>({
            method,
            url,
            data,
            headers,
            ...config
        }).then(response => response.data);
    };

    return {
        get: async <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
            return makeRequest<T>('get', url, undefined, config);
        },
        post: async <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
            return makeRequest<T>('post', url, data, config);
        },
        del: async <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
            return makeRequest<T>('delete', url, data, config);
        }
    };
}

// 处理登录失效
function handleUnauthorized() {
    const { $dialog } = window as any;
    $dialog.warning({
        title: '提示',
        content: '登录身份已失效，请重新登录!',
        positiveText: '确定',
        closable: false,
        maskClosable: false,
        onPositiveClick: () => {
            // localStorage.clear();
            // router.replace({path: '/login'});
            const userStore = useUserStore()
            userStore.$reset()
        },
    });
}

const service = createService();
const { get, post, del } = createRequest(service);

export { get, post, del };